import cssStyle from './index.module.css'
import React from 'react'
import ReactDOM from 'react-dom'
import { Model } from '../index'
import PropTypes from 'prop-types'

class LoadingComponent extends React.PureComponent{
    hideLoading = this.props.hideLoading.bind(this)
    componentDidMount(){
        window.addEventListener('hashchange', this.hideLoading)
    }
    componentWillUnmount(){
        window.removeEventListener('hashchange', this.hideLoading)
    }
    render(){
        return(
            <Model>
                <div className={ cssStyle.content }>
                    <span className={ cssStyle.icon }>
                        <span className="iconfont">&#xe627;</span>
                    </span>
                    <span className={ cssStyle.title }>{ this.props.title }</span>
                </div>
            </Model>
        )
    }
}

LoadingComponent.propTypes = {
    hideLoading: PropTypes.func,
    title: PropTypes.string
}

function showLoading(){
    let loadingContainer = null
    return{
        showLoading(title){
            loadingContainer = document.createElement('div')
            document.body.appendChild(loadingContainer)
            ReactDOM.render(
                <LoadingComponent title={ title } hideLoading={ this.hideLoading.bind(this) } />,
                loadingContainer
            )
        },
        hideLoading(){
            if(document.body.contains(loadingContainer)){
                ReactDOM.unmountComponentAtNode(loadingContainer)
                document.body.removeChild(loadingContainer)
            }
        }
    }
}

export default showLoading